package com.umeox.ota.data.local;

import android.content.res.AssetManager;
import android.os.Build;
import android.util.Log;

import com.abupdate.iot_libs.engine.thread.Dispatcher;
import com.abupdate.iot_libs.engine.thread.NamedCallable;
import com.abupdate.iot_libs.interact.response.CommonResponse;
import com.umeox.ota.data.constant.Constant;
import com.umeox.ota.gloable.App;
import com.umeox.ota.utils.DeviceUtil;
import com.umeox.ota.utils.FileUtils;
import com.umeox.ota.utils.RxTime;

import org.json.JSONObject;

import java.util.regex.Pattern;

/**
 * @author fighter_lee
 * @date 2018/2/27
 * 自定义配置，方便构建差异化配置
 */
public class CustomConfig {

    private static CustomConfig mInstance;
    private static final String TAG = "CustomConfig";
    public static final String KEY_MID_BACK = "key_mid_back";
    public String mid = "";
    public boolean requestPush = true;
    public boolean localUpdate = true;
    public boolean batteryJudge = true;
    public boolean screenJudge = true;
    public int fotaCheckCycle = 0;
    public String notifyType = NotifyType.DIALOG_NOTIFY.getType();

    public String oem;
    public String models;
    public String platform;
    public String deviceType;
    public String productId;
    public String productSecret;
    public String version;
    public String theme;
    private static String midType;


    public static CustomConfig getInstance() {
        if (mInstance == null) {
            synchronized (CustomConfig.class) {
                if (mInstance == null) {
                    mInstance = new CustomConfig();
                }
            }
        }
        return mInstance;
    }

    public CustomConfig() {
        getConfigFromConfigProp();
    }

    private void getConfigFromConfigProp() {
        try {
            AssetManager assetManager = App.sCx.getAssets();
            String config = FileUtils.inputStreamToString(assetManager.open("CustomConfig.json"));
            JSONObject configJson = new JSONObject(config);
            midType = TYPE_IMEI;
            if (configJson.has(KEY_CONFIG_MID_TYPE)) {
                midType = configJson.getString(KEY_CONFIG_MID_TYPE);
            }
            genMid();

            //获取是否需要升级推送功能
            if (configJson.has(KEY_CONFIG_PUSH)) {
                requestPush = configJson.getBoolean(KEY_CONFIG_PUSH);
            }

            //获取是否需要本地升级功能
            if (configJson.has(KEY_CONFIG_LOCAL_UPDATE)) {
                localUpdate = configJson.getBoolean(KEY_CONFIG_LOCAL_UPDATE);
            }

            //获取是否需要判断电量
            if (configJson.has(KEY_CONFIG_BATTERY_JUDGE)) {
                batteryJudge = configJson.getBoolean(KEY_CONFIG_BATTERY_JUDGE);
            }

            //获取是否需要判断息屏
            if (configJson.has(KEY_CONFIG_SCREEN_JUDGE)) {
                screenJudge = configJson.getBoolean(KEY_CONFIG_SCREEN_JUDGE);
            }

            //获取FOTA默认检测周期
            if (configJson.has(KEY_CONFIG_FOTA_CHECK_CYCLE)) {
                fotaCheckCycle = configJson.getInt(KEY_CONFIG_FOTA_CHECK_CYCLE);
            }

            //获取主体颜色字段
            if (configJson.has(KEY_CONFIG_THEME)) {
                if (Theme.valid(configJson.getString(KEY_CONFIG_THEME))) {
                    theme = configJson.getString(KEY_CONFIG_THEME);
                }
            }

            //获取配置的新版本提示方式
            if (configJson.has(KEY_CONFIG_NOTIFY)) {
                notifyType = configJson.getString(KEY_CONFIG_NOTIFY);
            }

            if (configJson.has(KEY_CONFIG_OEM)) {
                oem = configJson.getString(KEY_CONFIG_OEM);
            }

            if (configJson.has(KEY_CONFIG_MODELS)) {
                models = configJson.getString(KEY_CONFIG_MODELS);
            }

            if (configJson.has(KEY_CONFIG_PLATFORM)) {
                platform = configJson.getString(KEY_CONFIG_PLATFORM);
            }

            if (configJson.has(KEY_CONFIG_DEVICETYPE)) {
                deviceType = configJson.getString(KEY_CONFIG_DEVICETYPE);
            }

            if (configJson.has(KEY_CONFIG_PRODUCT_ID)) {
                productId = configJson.getString(KEY_CONFIG_PRODUCT_ID);
            }

            if (configJson.has(KEY_CONFIG_PRODUCT_SECRET)) {
                productSecret = configJson.getString(KEY_CONFIG_PRODUCT_SECRET);
            }

            if (configJson.has(KEY_CONFIG_VERSION)) {
                version = configJson.getString(KEY_CONFIG_VERSION);
            } else {
                version = Build.DISPLAY;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String obtainMid() {
        RxTime.newInstance()
                .setTimeout(10 * 1000)
                .setICondition(() -> DeviceUtil.isValidMid(genMid()))
                .execute();
        return genMid();
    }



    /**
     * @return 生成的 mid
     */
    private String genMid() {
        CommonResponse<String> genMidResponse = Dispatcher.getDispatcher().blockExecuted(new NamedCallable<String>("Get Mid") {
            @Override
            protected String execute() {
                switch (midType) {
                    case TYPE_IMEI:
                        mid = DeviceUtil.getIMEI();
                        break;
                    case TYPE_SN:
                        mid = DeviceUtil.getSN();
                        break;
                    case TYPE_MAC:
                        mid = DeviceUtil.getMAC();
                        break;
                    default:
                        mid = DeviceUtil.getSN();
                        break;
                }
                return mid;
            }
        });
        this.mid = genMidResponse.isOK ? genMidResponse.result : "";
        return mid;
    }

    private static final String TYPE_IMEI = "imei";
    private static final String TYPE_SN = "sn";
    private static final String TYPE_MAC = "mac";

    private static final String TYPE_SCREEN_PORTRAIT = "portrait";
    private static final String TYPE_SCREEN_LANDSCAPE = "landscape";

    private static final String TYPE_DIALOG_NOTIFY = "dialog_notify";
    private static final String TYPE_NOTIFICATION_NOTIFY = "notification_notify";

    private static final String KEY_CONFIG_MID_TYPE = "ro.fota.midType";
    private static final String KEY_CONFIG_PUSH = "ro.fota.push";
    private static final String KEY_CONFIG_LOCAL_UPDATE = "ro.fota.localUpdate";

    /**
     * 是否需要开启电量策略
     */
    private static final String KEY_CONFIG_BATTERY_JUDGE = "ro.fota.powerCondition";

    /**
     * 强制升级是否需要判断息屏
     */
    private static final String KEY_CONFIG_SCREEN_JUDGE = "ro.fota.screenCondition";

    /**
     * FOTA 默认检测周期, 默认 25 * 60 * 60 * 1000;
     */
    private static final String KEY_CONFIG_FOTA_CHECK_CYCLE = "ro.fota.fotaCheckCycle";
    private static final String KEY_CONFIG_ORIENTATION = "ro.fota.orientation";
    private static final String KEY_CONFIG_THEME = "ro.fota.theme";

    /**
     * 新版本提示方式,弹框/通知栏提示
     */
    private static final String KEY_CONFIG_NOTIFY = "ro.fota.reminder";

    private static final String KEY_CONFIG_OEM = "ro.fota.oem";
    private static final String KEY_CONFIG_MODELS = "ro.fota.device";
    private static final String KEY_CONFIG_PLATFORM = "ro.fota.platform";
    private static final String KEY_CONFIG_DEVICETYPE = "ro.fota.type";
    private static final String KEY_CONFIG_PRODUCT_ID = "ro.fota.productId";
    private static final String KEY_CONFIG_PRODUCT_SECRET = "ro.fota.productSecret";
    private static final String KEY_CONFIG_VERSION = "ro.fota.version";

    /**
     * 新版本提醒方式
     * ①弹框提醒
     * ②通知栏提醒
     */
    public enum NotifyType {
        DIALOG_NOTIFY(TYPE_DIALOG_NOTIFY), NOTIFICATION_NOTIFY(TYPE_NOTIFICATION_NOTIFY);
        private String type;

        NotifyType(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }
    }

    public static class Theme {
        private String data;

        Theme(String data) {
            this.data = data;
        }

        public String getData() {
            return data;
        }

        public static boolean valid(String datas) {
            String[] colors = datas.split(",");

            if (colors.length == 0) {
                return false;
            }

            String pattern = "(^#([A-Fa-f0-9]){6}$)|(^#([A-Fa-f0-9]){8}$)";
            boolean isMatch = false;
            for (String color : colors) {
                isMatch = Pattern.matches(pattern, color);
                //数组中若有任一个元素不能通过匹配则返回false
                if (!isMatch) {
                    return isMatch;
                }
            }
            return true;
        }
    }

    /**
     * 由于此方法会在初始化 sdk trace 模块之前调用，所以需要使用 log 方法打印
     *
     * @return 获取 DefaultMid，满足条件则返回 string，不满足的则返回 ""
     */
    public static String getDefaultMid() {
        String prefix = DeviceUtil.DEFAULT_SN;
        long now = System.currentTimeMillis();
        Log.d("iport", "now time: " + now);
        long initialTime = Installation.getCreateTime();
        Log.d("iport", "initial time: " + initialTime);
        int obtainTime = ((App) App.sCx).getDB().queryObtainMidTime();
        Log.d("iport", "obtain time: " + obtainTime);
        //是否开启 default-mid 策略，记录的获取
        boolean onDefaultMidPolicy = (now - initialTime) > Constant.DEFAULT_MID_POLICY_EFFECTIVE_TIME
                || obtainTime > Constant.DEFAULT_MID_POLICY_EFFECTIVE_NUMBER;
        Log.d("iport", "default-mid whether to open: " + now);

        if (onDefaultMidPolicy) {
            switch (midType) {
                case TYPE_IMEI:
                    prefix = DeviceUtil.DEFAULT_IMEI;
                    break;
                case TYPE_SN:
                    prefix = DeviceUtil.DEFAULT_SN;
                    break;
                case TYPE_MAC:
                    prefix = DeviceUtil.DEFAULT_MAC;
                    break;
                default:
                    break;
            }
        } else {
            return "";
        }
        return prefix + "-" + DeviceUtil.getInstallationId();
    }
}
